import {
	showToast
} from './common'
import qs from '../qs/qs.js'
import md5 from '../js_sdk/js-md5/src/md5.js'

// const BASE_URL = "http://192.168.10.149:8040";
// const BASE_URL = "http://api.yuzhekeji.club";
export const BASE_URL = "http://192.168.10.81:8041"
// const BASE_URL = "http://39.97.242.0:9002/kxy-app-api"
// const BASE_URL = "https://admin.mkkxy.com:9015/kxy-app-api"

const HEADER = () => ({
	"Content-Type": "application/x-www-form-urlencoded",
	"TenantId": uni.getStorageSync('tenantId') || '',
	// "Client": "APP"
})
async function request_md5(url, data = {}, isShowToast = false) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中...'
		})
		let time = new Date().getTime() + uni.getStorageSync('timeDiff')
		data = Object.assign(data, {
			't': time,
			'token': uni.getStorageSync('token') || '',
			'nonce': parseFloat(Math.random() + 1).toFixed(10) * 1e10
		})
		let dataKeys = Object.keys(data)
		let _data = {}
		let data_ = {}
		if (dataKeys.length) {
			dataKeys.sort().forEach(x => {
				if (typeof data[`${x}`] === 'number' || typeof data[`${x}`] === 'string') {
					if (data[`${x}`] !== undefined && data[`${x}`] !== '') _data[`${x}`] = data[`${x}`]
				}
				if (Object.prototype.toString.call(data[`${x}`]) === '[object Array]') {
					if (data[`${x}`].length) _data[`${x}`] = data[`${x}`]
				}
			})
		}
		_data.secret = uni.getStorageSync('secret') || ''
		let dataString = ''
		for (let i in _data) {
			if (dataString !== '') {
				dataString = dataString.concat('&', `${i}=${_data[i]}`)
			} else {
				dataString = `${i}=${_data[i]}`
			}
		}
		// data_.sign = md5(encodeURIComponent(dataString)).toUpperCase()
		data_.sign = md5(dataString).toUpperCase()
		data_.token = uni.getStorageSync('token') || ''
		data_.t = time
		data_ = Object.assign(data_, data)
		data = qs.stringify(data_)
		uni.request({
			url: `${BASE_URL}${url}`,
			data: data,
			method: 'POST',
			header: HEADER(),
			success: function(res) {
				if (res.statusCode == 401 || res.data.code == 401) {
					showToast('登录状态失效，请重新登录');
					uni.setStorageSync('token', '');
					uni.setStorageSync('userId', '');
					uni.setStorageSync('checkAdd', '');
					uni.setStorageSync('tenantId', '');
					uni.setStorageSync('examIndex', 0);
					uni.setStorageSync('notice', []);
					uni.reLaunch({
						url: '/pages/login/login'
					});
					return false
				}
				if (res.statusCode === 500) {
					showToast(`${res.data.msg}`);
					return false
				}
				if (res.data.code === 500) {
					if (isShowToast) {
						showToast(`${res.data.msg}`);
					}
					return resolve(res.data)
					// setTimeout(_ => uni.navigateBack(), 1e3);
				}
				return resolve(res.data)
			},
			fail: function(err) {
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	})
}

async function request(url, data = {}) {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '加载中...'
		})
		uni.request({
			url: `${BASE_URL}${url}`,
			data: data,
			method: 'POST',
			header: HEADER(),
			success: function(res) {
				if (res.statusCode == 401 || res.data.code == 401) {
					showToast('登录状态失效，请重新登录');
					uni.setStorageSync('token', '');
					uni.setStorageSync('userId', '');
					uni.setStorageSync('checkAdd', '');
					uni.setStorageSync('tenantId', '');
					uni.setStorageSync('examIndex', 0);
					uni.setStorageSync('notice', []);
					uni.reLaunch({
						url: '/pages/login/login'
					});
					return false
				}
				if (res.data.code === 500) {
					showToast(`${res.data.msg}`);
					// setTimeout(_ => uni.navigateBack(), 1e3);
					return false
				}
				return resolve(res.data)
			},
			fail: function(err) {
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	})
}

export const post_md5 = (url, data, isShowToast) => request_md5(url, data, isShowToast)
export const post = (url, data) => request(url, data)

export const request_integral = (code, reId) => {
	return new Promise((resolve, reject) => {
		let ruleCode = {
			'login': 100000,
			'news': 200000,
			'placard': 300000,
			'daily_ok': 400001,
			'daily_err': 400002,
			'simulation_ok': 400010,
			'simulation_err': 400011,
			'exam_ok': 400100,
			'exam_err': 400101,
			'make_ok': 400102,
			'make_err': 400103,
			'video': 500000,
			'image': 500001,
			'file': 500002,
			'exam': 500003,
			'course': 500004,
		};
		let data = {
			code: ruleCode[code],
			userId: uni.getStorageSync('userId'),
			reId: reId
		}
		post_md5('/integral-app/integral/usergrade/addgrade', data).then(res => {
			return resolve(res)
		}).catch(err => {
			return reject(err)
		})
	})
}
